<template>
  <div class="main-container">
    <div class="header">
      <div style="display: flex; align-items: center;">
        <el-icon size="24" style="margin-right: 10px;"><Monitor /></el-icon>
        <h2>设备管理系统</h2>
      </div>
      <div style="display: flex; align-items: center;">
        <span style="margin-right: 15px;">欢迎，{{ username }}</span>
        <el-button type="text" @click="handleLogout" style="color: white;">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-button>
      </div>
    </div>
    
    <div class="content">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3>{{ isEdit ? '编辑设备' : '添加设备' }}</h3>
        <el-button @click="$router.push('/devices')">
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
      </div>
      
      <el-card style="max-width: 800px; margin: 0 auto;">
        <el-form :model="deviceForm" :rules="rules" ref="deviceFormRef" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备型号" prop="deviceModel">
                <el-input v-model="deviceForm.deviceModel" placeholder="请输入设备型号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备IMEI" prop="deviceImei">
                <el-input v-model="deviceForm.deviceImei" placeholder="请输入设备IMEI" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备Token" prop="deviceToken">
                <el-input v-model="deviceForm.deviceToken" placeholder="请输入设备Token" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备备注">
                <el-input v-model="deviceForm.deviceRemark" placeholder="请输入设备备注（可选）" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="loading">
              {{ isEdit ? '保存修改' : '添加设备' }}
            </el-button>
            <el-button @click="$router.push('/devices')">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'DeviceForm',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const deviceFormRef = ref()
    const loading = ref(false)
    const username = ref(sessionStorage.getItem('username') || '')
    
    const isEdit = computed(() => route.params.id !== undefined)
    
    const deviceForm = reactive({
      deviceModel: '',
      deviceImei: '',
      deviceToken: '',
      deviceRemark: ''
    })
    
    const rules = {
      deviceModel: [
        { required: true, message: '请输入设备型号', trigger: 'blur' }
      ],
      deviceImei: [
        { required: true, message: '请输入设备IMEI', trigger: 'blur' }
      ],
      deviceToken: [
        { required: true, message: '请输入设备Token', trigger: 'blur' }
      ]
    }
    
    const loadDevice = async () => {
      if (!isEdit.value) return
      
      try {
        loading.value = true
        const token = sessionStorage.getItem('token')
        const response = await axios.get(`/api/devices/${route.params.id}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        Object.assign(deviceForm, response.data)
      } catch (error) {
        ElMessage.error('加载设备信息失败')
        router.push('/devices')
      } finally {
        loading.value = false
      }
    }
    
    const handleSubmit = async () => {
      try {
        await deviceFormRef.value.validate()
        loading.value = true
        
        const token = sessionStorage.getItem('token')
        const username = sessionStorage.getItem('username')
        const headers = { Authorization: `Bearer ${token}` }
        Object.assign(deviceForm, {"email": username})
        
        if (isEdit.value) {
          await axios.put(`/api/devices/${route.params.id}`, deviceForm, { headers })
          ElMessage.success('设备更新成功')
        } else {
          await axios.post('/api/devices', deviceForm, { headers })
          ElMessage.success('设备添加成功')
        }
        
        router.push('/devices')
      } catch (error) {
        if (error.response?.data?.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('操作失败，请重试')
        }
      } finally {
        loading.value = false
      }
    }
    
    const handleLogout = () => {
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('username')
      router.push('/login')
    }
    
    onMounted(() => {
      loadDevice()
    })
    
    return {
      deviceForm,
      deviceFormRef,
      rules,
      loading,
      username,
      isEdit,
      handleSubmit,
      handleLogout
    }
  }
}
</script> 